<template>
  <a-modal :visible="visible" width="50%" @cancel="cancel" @ok="submitData">
    <template #title>
      {{ type === 0 ? '创建流程模版' : '编辑流程模版' }}
    </template>
    <div class="content">
      <div class="nodes-display">
        <a-row
          v-for="(row, index) in nodeRows"
          :key="`row-${index}`"
          :gutter="10"
          :class="index % 2 === 1 ? 'node-row flexEnd' : 'node-row'"
        >
          <a-col
            v-for="(node, node_index) in index % 2 === 1 ? row.reverse() : row"
            :key="`row-${index}-node-${node_index}`"
            :span="6"
          >
            <div
              :class="`node-item ${node.isStart ? 'start-node' : ''} ${
                node.isEnd ? 'end-node' : ''
              }`"
            >
              <div class="node-num"> {{ node['_index'] }} </div>
              <div class="node-name">
                {{ node.name }}
              </div>
              <div
                v-if="
                  !(
                    index % 2 === 0 &&
                    node_index === row.length - 1 &&
                    node.isEnd
                  )
                "
                :class="`line ${node_index === 3 ? 'end-line' : ''}`"
              ></div>
              <div
                v-if="
                  index % 2 === 1 &&
                  node_index === 0 &&
                  index < nodeRows.length - 1
                "
                class="link-left"
              ></div>
              <div
                v-if="
                  index % 2 === 0 &&
                  node_index === 3 &&
                  index < nodeRows.length - 1
                "
                class="link-right"
              ></div>
            </div>
          </a-col>
        </a-row>
      </div>
      <a-form
        ref="formRef"
        :model="formData"
        label-align="left"
        style="margin-top: 12px"
        :rules="rules"
      >
        <a-row>
          <a-col :span="24">
            <div class="title">
              <div class="text">
                <img
                  src="@/assets/images/check/Frame@2x.png"
                  alt=""
                  style="width: 17px; height: 17px"
                />
                <span class="text-font">流程模版基本信息</span>
              </div>
              <div class="file-count"> </div>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-top: 16px">
          <a-col :span="12">
            <a-form-item
              field="name"
              label="流程模版名称"
              label-col-flex="100px"
            >
              <a-input v-model="formData.name" placeholder="请输入名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="description"
              label="流程模版说明"
              label-col-flex="100px"
            >
              <a-input
                v-model="formData.description"
                placeholder="请输入编码"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-divider></a-divider>
      <a-form ref="nodeRef" :model="nodeDataMap" label-align="left">
        <a-row style="margin-bottom: 16px">
          <a-col :span="24">
            <div class="title">
              <div class="text">
                <img
                  src="@/assets/images/check/Frame@2x.png"
                  alt=""
                  style="width: 17px; height: 17px"
                />
                <span class="text-font">流程节点配置</span>
              </div>
              <div class="file-count">
                <a-button type="text" @click="addNode">新增节点</a-button></div
              >
            </div>
          </a-col>
        </a-row>
        <a-row
          v-for="(node, index) in nodeData"
          :key="`node-${index}`"
          :gutter="24"
        >
          <a-col :span="12">
            <a-form-item
              :field="`name-${index}`"
              :label="`节点${index}名称`"
              label-col-flex="100px"
              :rules="[{ required: true, message: '请输入名称' }]"
              :validate-trigger="['change', 'input']"
            >
              <a-input v-model="node.name" placeholder="请输入名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :field="`user-${index}`"
              label="审核人"
              label-col-flex="90px"
              :rules="[{ required: true, message: '请选择审核人' }]"
              :validate-trigger="['change', 'input']"
            >
              <UserSelector
                v-model:model-value="node.userNameStr"
                :using-name="true"
                :multiple="true"
              ></UserSelector>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, defineEmits, defineProps, ref, watch } from 'vue';
  import UserSelector from '@/components/user-selector/index.vue';
  import { useRoute } from 'vue-router';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { genXMLByNodes } from './common/gen-process';
  import { createProcess, deployProcess, updateProcess } from './api';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    type: {
      type: Number,
      default: 0,
    },
    defaultProcess: {
      type: Object,
      default() {
        return {};
      },
    },
  });
  const route = useRoute();
  const emits = defineEmits(['update:visible', 'submit', 'update']);
  const formRef = ref<FormInstance>();
  const nodeRef = ref<FormInstance>();
  const rules = ref({
    name: [
      {
        required: true,
        message: '请输入名称',
      },
    ],
    description: [
      {
        required: true,
        message: '请输入说明',
      },
    ],
  });
  const formData = ref({
    name: '',
    description: '',
  });
  const nodeData = ref<any[]>([]);
  const nodeDataMap = computed(() => {
    const map: any = {};
    nodeData.value?.forEach((e, index) => {
      map[`name-${index}`] = e.name;
      map[`user-${index}`] = e.userNameStr;
    });
    console.log('map: ', map);
    return map;
  });
  const nodeRows = computed(() => {
    const rows: any = [];
    const nodes: any[] = JSON.parse(JSON.stringify(nodeData.value));
    const startNode = {
      name: '发起',
      isStart: true,
    };
    const endNode = {
      name: '结束',
      isEnd: true,
    };
    nodes.unshift(startNode);
    nodes.push(endNode);
    for (let i = 0; i < nodes.length; i += 4) {
      const row = [];
      for (let j = i; j < i + 4; j += 1) {
        if (j < nodes.length) {
          // eslint-disable-next-line no-underscore-dangle
          nodes[j]._index = j + 1;
          row.push(nodes[j]);
        }
      }
      rows.push(row);
    }
    return rows;
  });
  const addNode = () => {
    const num = nodeData.value.length;
    nodeData.value.push({
      name: `节点${num}`,
      userNameStr: '',
    });
  };

  const cancel = () => {
    nodeData.value = [];
    emits('update:visible', false);
  };
  const submitData = async (): Promise<string> => {
    let validate = true;
    if (!nodeData.value.length) {
      Message.error('请添加审批节点！');
      return '';
    }
    nodeData.value.forEach((e) => {
      if (!e.name || !e.userNameStr) {
        validate = false;
      }
    });
    await formRef.value?.validate();
    await nodeRef.value?.validate();
    if (!validate) {
      Message.error('请完善节点名称或审核人信息！');
      return '';
    }
    if (!formData?.value?.description || !formData?.value?.name) {
      Message.error('请完善基本信息！');
      return '';
    }
    const { variable, processConfig, xml, userTaskIds } = await genXMLByNodes(
      nodeData.value,
      {
        name: formData?.value?.name,
      }
    );
    const processUser = nodeData.value.map((e, index) => {
      const node = JSON.parse(JSON.stringify(e));
      node.USER_TASK_ID = userTaskIds[index];
      return node;
    });
    const params = {
      ...props.defaultProcess,
      variable: JSON.stringify(variable),
      modelKey: processConfig.processId || '',
      modelName: processConfig.name || '',
      bpmnXml: xml,
      projectId: route.params.projectId || '',
      describe: formData.value?.description || '',
      processUser: JSON.stringify(processUser),
      BPM_CUSTOM_EXT: '',
    };
    if (props.type === 0) {
      createProcess(params).then((res: any) => {
        if (res.code === 8000000) {
          Message.success('创建成功！');
          emits('submit', true);
          cancel();
        }
      });
    } else {
      updateProcess(params).then((res: any) => {
        if (res.code === 8000000) {
          Message.success('修改成功！');
          emits('update', true);
          cancel();
        }
      });
    }
    return '';
  };

  const init = () => {
    if (props.type === 1) {
      console.log(props.type);
      formData.value = {
        name: props.defaultProcess.name,
        description: props.defaultProcess.describe,
      };
      nodeData.value = JSON.parse(props.defaultProcess.processUser) || [];
    }
  };
  watch(
    () => props.visible,
    (val) => {
      if (val) {
        init();
      }
    }
  );
</script>

<style scoped lang="less">
  .nodes-display {
    min-height: 100px;
    //border: 1px solid red;
    padding-left: 50px;
    padding-right: 50px;
    .flexEnd {
      justify-content: flex-end !important;
    }
    .node-row {
      padding-top: 8px;
      //padding-bottom: 8px;
      margin-top: 8px;
      //border-top: 1px solid var(--color-border-2);
      height: 40px;
      position: relative;
      &:first-child {
        border-top: 0px;
      }
    }
    .node-item {
      display: flex;
      justify-content: left;
      align-items: center;
      align-content: center;
      position: relative;
      //border: 1px solid black;

      .node-num {
        height: 28px;
        width: 28px;
        border-radius: 14px;
        background-color: var(--color-fill-2);
        text-align: center;
        line-height: 28px;
      }
      .node-name {
        margin-left: 8px;
        max-width: calc(100% - 70px);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding-right: 8px;
      }
      .line {
        height: 0px;
        border-bottom: 1px solid var(--color-border-2);
        //width: 60px;
        flex: 1;
      }
    }
    .link-left {
      height: 48px;
      width: 40px;
      position: absolute;
      top: 14px;
      left: -44px;
      border: 1px solid var(--color-border-2);
      border-right: 0px;
    }
    .link-right {
      height: 48px;
      width: 2px;
      position: absolute;
      top: 14px;
      right: 0px;
      border: 1px solid var(--color-border-2);
      border-left: 0px;
    }
    .start-node {
      .node-num {
        background-color: rgb(var(--arcoblue-6));
        color: white;
      }
    }
  }
  .title {
    position: relative;
    .text {
      display: flex;
      align-content: center;
      align-items: center;
    }
    .text-font {
      display: inline-block;
      font-size: 14px;
      font-weight: 600;
      margin-left: 8px;
    }
    .file-count {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
</style>
